package milu.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import javax.jdo.PersistenceManager;
import milu.models.*;
import milu.*;
import java.io.UnsupportedEncodingException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

public class Login extends HttpServlet {

	public void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

        request.getRequestDispatcher("/login.jsp").forward(request, response);

    }
	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
        try {
            // TODO do some validation
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            String returnurl = request.getParameter("returnurl");

            PersistenceManager pm = Datastore.getPersistenceManager();
            String query = "select from " + MyUser.class.getName() + " where email == \""+ email +"\" && password == \""+SimpleSHA1.SHA1(password)+"\"";
            List<MyUser> foundUsers = (List<MyUser>)pm.newQuery(query).execute();
            if(foundUsers.size() == 0) { // user not found
                request.setAttribute("error", "Utente non trovato");
                request.getRequestDispatcher("/login.jsp?returnurl="+returnurl).forward(request, response);
                return;
            }
            // user found
            Key userKey = foundUsers.get(0).getKey();
            LOG.info("userKey: "+userKey);

            HttpSession session = request.getSession(true);
            session.setAttribute("userKey", userKey);

            response.sendRedirect(returnurl);
        } catch (NoSuchAlgorithmException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace();
        } 
    }
}
